#include <iostream>
#include <vector>
#include <string>
#include <pthread.h>
#include <unistd.h>

pthread_mutex_t gmutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t gcond = PTHREAD_COND_INITIALIZER;

void* MasterCore(void* args)
{
    std::string name = static_cast<const char*>(args);
    while(true)
    {
        pthread_mutex_lock(&gmutex);

        std::cout << "Master唤醒一个线程" << std::endl;
        // pthread_cond_signal(&gcond); //唤醒一个线程
        pthread_cond_broadcast(&gcond); //唤醒多个线程

        pthread_mutex_unlock(&gmutex);
        sleep(1);
    }
}

void* SlaverCore(void* args)
{
    std::string name = static_cast<const char*>(args);
    while(true)
    {
        pthread_mutex_lock(&gmutex);

        //当前线程在等待是还是持有锁的，所以wait: 1.让调用线程等待 2.自动释放持有锁，让其他线程进入临界区
        pthread_cond_wait(&gcond, &gmutex);
        std::cout << name << " 被唤醒了 "<< std::endl;

        pthread_mutex_unlock(&gmutex);
    }
}

void StartMaster(std::vector<pthread_t>& tids)
{
    pthread_t tid;
    int n = pthread_create(&tid, nullptr, MasterCore, (void*)"Master Thread");
    if(!n)
    {
        std::cout << "master thread create success" << std::endl;
    }
    tids.emplace_back(tid);
}

void StartSlaver(std::vector<pthread_t>& tids, int num = 3)
{
    for (int i = 0; i < num; i++)
    {
        pthread_t tid;
        char* buff = new char[64];
        snprintf(buff, 64, "slaver-%d", i + 1);
        int n = pthread_create(&tid, nullptr, SlaverCore, (void*)buff);
        if(!n)
        {
            std::cout << buff << " create success"<< std::endl;
        }
        tids.emplace_back(tid);
    }
}

void WaitAll(const std::vector<pthread_t>& tids)
{
    for (auto& tid : tids)
        pthread_join(tid, nullptr);
}

int main()
{
    std::vector<pthread_t> tids;
    StartMaster(tids);
    StartSlaver(tids);
    WaitAll(tids);
    return 0;
}